<template>
  <div class="page-miH page-bgBack">
    <div class="main-content-header">
      <a-input v-model="query" placeholder="搜索印章名称" style="width: 200px" @pressEnter="search" :allowClear="true">
        <a-icon slot="suffix" type="search" @click="search" />
      </a-input>
      <div style="display: flex">
        <a-button v-if="isContainByString('contractAdmin')" type="primary" @click="showIssueModa" style="margin-right: 10px">
          下发印章
        </a-button>
        <a-button type="primary" class="mr12" @click="addStampCreate" v-if="showSealEdit"> <a-icon type="plus" />上传印章 </a-button>
        <a-button type="primary" @click="goStampCreate" v-if="showSealEdit"> <a-icon type="plus" />添加印章 </a-button>
      </div>
    </div>
    <div class="main-content-main" style="height: 78vh">
      <a-table
        :columns="columns"
        :data-source="list"
        row-key="id"
        :scroll="{ y: editorHeight }"
        class="seal-table"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <img slot="sealString" slot-scope="sealString" :src="sealString" style="width: 64px; height: auto" />
        <img slot="legalPersonPicture" slot-scope="legalPersonPicture" :src="legalPersonPicture" style="width: 64px; height: auto" />
        <span slot="status" slot-scope="status" style="text-align: center">{{ status === 1 ? "已认证" : "未认证" }}</span>
        <span slot="action" slot-scope="record" class="action">
          <template v-if="record.status !== 1">
            <span class="edit" v-if="record.content === '此印章是上传的'" @click="editStamp(record)">编辑</span>
            <span class="edit" v-else @click="goStampUpdate(record)">编辑</span>
            <a-divider type="vertical" />
            <span class="edit" @click="goStampVerify(record)">认证</span>
            <a-divider type="vertical" />
          </template>
          <a-popconfirm title="确定要删除这个印章吗？" ok-text="确定" cancel-text="取消" @confirm="deleteStamp(record)">
            <span class="edit">删除</span>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <a-modal
      :visible="issueModalVisible"
      title="下发印章"
      width="538px"
      @ok="confirmIssueModal"
      :destroy-on-close="true"
      @cancel="handleCancelIssueModal"
    >
      <a-row style="width: 500px">
        <a-col :span="12">
          <span>请选择印章</span>
          <a-select
            v-model="contractList"
            show-search
            option-filter-prop="children"
            :filter-option="filterOption"
            mode="multiple"
            placeholder="请选择印章"
            style="width: 240px; margin-top: 10px"
          >
            <a-select-option :disabled="item.status !== 1" v-for="(item, index) in contractData" :key="index" :value="item.id">
              <a-tooltip placement="left" :title="item.name">
                {{ item.name }}
              </a-tooltip>
            </a-select-option>
          </a-select>
          <div style="margin-top: 10px">（未认证印章不允许下发）</div>
        </a-col>
        <a-col :span="12">
          <span>请选择下发用工单位</span>
          <a-tree-select
            :value="companyList"
            :treeData="dataList"
            :filterTreeNode="filterTreeNode"
            treeCheckable
            placeholder="请选择用工单位"
            style="width: 240px; margin-top: 10px; max-height: 350px; overflow: auto"
            @change="companySelectChange"
          />
        </a-col>
      </a-row>
    </a-modal>
    <!-- 上传印章 -->
    <a-modal
      :title="`${stateStamp === 'add' ? '新建' : '编辑'}印章`"
      :visible="visibleSeal"
      :confirm-loading="confirmLoadingSeal"
      @ok="handleOkSeal"
      @cancel="handleCancelSeal"
    >
      <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="印章名称">
          <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入印章名称!' }] }]" />
        </a-form-item>
        <a-form-item label="公司全称">
          <a-input v-decorator="['roundText', { rules: [{ required: false, message: '请输入公司全称!' }] }]" />
        </a-form-item>
        <a-form-item label="法人姓名">
          <a-input v-decorator="['legalPerson', { rules: [{ required: false, message: '请输入法人姓名!' }] }]" />
        </a-form-item>
        <a-form-item label="印章图片">
          <a-upload
            name="files"
            accept=".jpg, .jpeg, .png, .bmp, .svg, .gif"
            list-type="picture-card"
            :file-list="fileList"
            action="/file/api/v1/site/upload/inline"
            v-decorator="['sealString', { rules: [{ required: true, message: '请选择印章图片!' }] }]"
            @change="handleChange"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img width="100%" :src="previewImage" alt="example" />
          </a-modal>
        </a-form-item>
        <a-form-item label="法人章图片">
          <a-upload
            name="files"
            accept=".jpg, .jpeg, .png, .bmp, .svg, .gif"
            list-type="picture-card"
            :file-list="fileListLP"
            action="/file/api/v1/site/upload/inline"
            v-decorator="['legalPersonPicture', { rules: [{ required: false, message: '请选择法人章图片!' }] }]"
            @change="handleLPChange"
            @preview="handlePreview"
          >
            <div v-if="fileListLP.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img width="100%" :src="previewImage" alt="example" />
          </a-modal>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
import { mapGetters } from "vuex";
import { sealListAllReq, sealDeleteReq } from "@/api/company/contract";
import { findCompanyGroup } from "@/api/company/contract";
import { isContainByString } from "@/utils/index";
import { saveIssuedSeal, saveSeals, sealUpdateReq } from "./api";
import { formatCompanyTree } from "@/utils/tools";
export default {
  data() {
    return {
      stateStamp: "",
      recodeStamp: {},
      previewImage: "",
      fileList: [],
      fileListLP: [],
      previewVisible: false,
      imageUrl: "",
      formLayout: "horizontal",
      form: this.$form.createForm(this, { name: "coordinated" }),
      visibleSeal: false,
      confirmLoadingSeal: false,
      query: "",
      loading: false,
      columns: [
        {
          title: "印章图片",
          dataIndex: "sealString",
          key: "sealString",
          width: 200,
          scopedSlots: { customRender: "sealString" }
        },
        {
          title: "法人章图片",
          dataIndex: "legalPersonPicture",
          key: "legalPersonPicture",
          width: 200,
          scopedSlots: { customRender: "legalPersonPicture" }
        },
        {
          title: "印章名称",
          dataIndex: "name",
          key: "name"
        },
        {
          title: "公司全称",
          dataIndex: "roundText",
          key: "roundText"
        },
        {
          title: "法人姓名",
          dataIndex: "legalPerson",
          key: "legalPerson"
        },
        {
          title: "认证状态",
          dataIndex: "status",
          key: "status",
          scopedSlots: { customRender: "status" }
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" }
        }
      ],
      list: [],
      dataList: [],
      editorHeight: 0,
      companyId: this.$store.state.hr.companyId,
      issueModalVisible: false,
      // 下发选择框数据
      contractData: [],
      // 已选的模板数据
      contractList: [],
      // 已选的公司数据
      companyList: [],
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      }
    };
  },
  computed: {
    ...mapGetters(["isJF"]),
    showSealEdit() {
      const isAdmin = isContainByString("contractAdmin");
      return isAdmin || this.isJF;
    }
  },
  created() {
    this.findCompanyGroup();
    this.sealListAll();
  },
  mounted() {
    if (document.getElementById("editor-main")) {
      this.editorHeight = document.getElementById("editor-main").offsetHeight - 40;
    }
    const st = this.$route.query.operateFromShortcut;
    if (st === "shangchuanyinzhang") {
      this.$nextTick(() => {
        this.addStampCreate();
      });
    }
  },
  methods: {
    filterTreeNode(inVal, node) {
      if (node.data.props.title.toLowerCase().indexOf(inVal.toLowerCase()) >= 0) {
        return true;
      }
      return false;
    },
    companySelectChange(companyKeys) {
      this.companyList = companyKeys.filter((item) => item.includes("_company_"));
    },
    filterOption(input, option) {
      try {
        return option.componentOptions.children[0].componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      } catch (err) {
        return false;
      }
    },
    isContainByString,
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
    },
    editStamp(e) {
      console.log(e);
      this.stateStamp = "edit";
      this.recodeStamp = e;
      this.visibleSeal = true;
      this.$nextTick(() => {
        this.form.setFieldsValue(e);
        this.fileList = [
          {
            uid: "-2",
            name: "image.png",
            status: "done",
            url: e.sealString
          }
        ];
        if (e.legalPersonPicture) {
          this.fileListLP = [
            {
              uid: "-2",
              name: "image.png",
              status: "done",
              url: e.legalPersonPicture
            }
          ];
        } else {
          this.fileListLP = [];
        }
      });
    },
    handleCancel() {
      this.previewVisible = false;
    },
    // 添加印章addStampCreate
    addStampCreate() {
      this.stateStamp = "add";
      this.visibleSeal = true;
      this.recodeStamp = {};
      this.form.resetFields();
      this.fileList = [];
      this.fileListLP = [];
    },
    handleOkSeal() {
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          values.sealString = values.sealString.file ? values.sealString.file.thumbUrl : values.sealString;
          values.legalPersonPicture = values.legalPersonPicture
            ? values.legalPersonPicture.file
              ? values.legalPersonPicture.file.thumbUrl
              : values.legalPersonPicture
            : "";
          values.isLegalPerson = !!values.legalPersonPicture;
          values.subjectId = this.isContainByString("contractAdmin") ? "0" : this.companyId;
          values.content = "此印章是上传的";
          this.confirmLoadingSeal = true;
          if (this.stateStamp === "edit") {
            console.log("this.recodeStamp", this.recodeStamp);
            values.id = this.recodeStamp.id;
            sealUpdateReq(values)
              .then((res) => {
                this.confirmLoadingSeal = false;
                this.$message.success(res.msg);
                this.visibleSeal = false;
                this.sealListAll();
              })
              .catch((err) => {
                this.confirmLoadingSeal = false;
                console.log(err);
              });
          } else {
            saveSeals(values)
              .then((res) => {
                this.confirmLoadingSeal = false;
                this.$message.success(res.msg);
                this.visibleSeal = false;
                this.sealListAll();
              })
              .catch((err) => {
                this.confirmLoadingSeal = false;
                console.log(err);
              });
          }
        }
      });
    },
    handleCancelSeal() {
      this.visibleSeal = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ fileList }) {
      this.fileList = fileList;
      if (fileList.length === 0) {
        this.$nextTick(() => {
          this.form.resetFields(["sealString"]);
        });
      }
    },
    handleLPChange({ fileList }) {
      this.fileListLP = fileList;
      if (fileList.length === 0) {
        this.$nextTick(() => {
          this.form.resetFields(["legalPersonPicture"]);
        });
      }
    },
    treeSearch(e) {
      this.findCompanyGroup(e);
    },
    findCompanyGroup(e) {
      findCompanyGroup({ name: e || null })
        .then((res) => {
          this.dataList = formatCompanyTree(res.data);
          this.companyList = JSON.parse(JSON.stringify(this.companyList));
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    search() {
      if (this.query.length > 0) {
        this.sealListAll(this.query);
      } else {
        this.sealListAll();
      }
    },
    deleteStamp(record) {
      sealDeleteReq([record.id])
        .then((res) => {
          this.$message.success("印章删除成功");
          this.sealListAll();
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    goStampVerify(record) {
      this.$router.push(`/${this.isContainByString("contractAdmin") ? "contractAdmin" : "contract"}/stamp/verify/${record.id}`);
    },
    goStampUpdate(record) {
      this.$router.push(`/${this.isContainByString("contractAdmin") ? "contractAdmin" : "contract"}/stamp/update/${record.id}`);
    },
    goStampCreate() {
      this.$router.push(`/${this.isContainByString("contractAdmin") ? "contractAdmin" : "contract"}/stamp/create`);
    },
    sealListAll(query) {
      this.loading = true;
      sealListAllReq({
        name: query,
        subjectId: this.isContainByString("contractAdmin") ? "0" : this.companyId
      })
        .then((res) => {
          this.list = res.data;
          this.contractData = res.data;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    saveIssuedSeal() {
      if (this.companyList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的公司"
        });
        return;
      }
      if (this.contractList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的合同模板"
        });
        return;
      }
      const companyArr = Array.from(new Set(this.companyList.map((item) => item.split("_")[2])));
      const data = {
        subjectIds: companyArr,
        categoryIds: this.contractList
      };
      saveIssuedSeal(data)
        .then((res) => {
          this.issueModalVisible = false;
          this.$notification["success"]({
            message: "成功",
            description: "下发成功"
          });
          this.companyList = [];
          this.contractList = [];
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          // this.$notification["error"]({
          //   message: "错误",
          //   description: "下发失败"
          // });
        });
    },

    // 方法
    confirmIssueModal() {
      // TODO 下发接口
      // this.issueModalVisible = false;
      this.saveIssuedSeal();
    },
    handleCancelIssueModal() {
      this.issueModalVisible = false;
      // 已选的合同模板数据
      this.contractList = [];
      // 已选的公司数据
      this.companyList = [];
    },
    showIssueModa() {
      this.issueModalVisible = true;
    }
  }
};
</script>
<style lang="scss">
.seal-table {
  .action {
    a {
      color: var(--primary);
    }
  }
}
.edit {
  color: var(--primary);
  cursor: pointer;
}
</style>
